package com.ruoyi.word.service.impl;

import com.ruoyi.common.domain.word.CommonRa;
import com.ruoyi.word.dao.mapper.CommonRaMapper;
import com.ruoyi.word.service.ICommonRaService;
import com.ruoyi.word.service.ICommonWordRaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CommonRaServiceImpl implements ICommonRaService {

    @Autowired
    private CommonRaMapper dao;

    @Autowired
    private ICommonWordRaService wordRaService;

    @Override
    public List<CommonRa> findByWhereStr(String whereStr, String orderField, String order) {
        return dao.findByWhereStr(whereStr, orderField, order);
    }

    @Override
    public boolean exists(String name, Integer type) {
        return dao.exists(name, type);
    }

    // @Scheduled(fixedDelay = 1000*60*60*24*365)
    @Override
    public int buildRa() {
        List<Map<String, Object>> ras = wordRaService.findAllRa();
        ras.stream().forEach(d -> {
            String name = d.getOrDefault("name", "").toString().trim();
            Integer type = Integer.valueOf(d.get("type").toString());
            Integer count = Integer.valueOf(d.get("count").toString());
            saveOrUpdate(new CommonRa(name, type, count));
        });
        return ras.size();
    }

    @Override
    public int save(CommonRa record){
        return dao.insertSelective(record);
    }

    private int saveOrUpdate(CommonRa record) {
        CommonRa _ra = dao.findByNameAndType(record.getName(), record.getType());
        if(_ra != null) {
            record.setId(_ra.getId());
            record.setUpdateTime(new Date());
            // 排除不需要更新的字段
            record.setAddTime(null);
            record.setName(null);
            record.setType(null);
            return dao.updateByPrimaryKeySelective(record);
        }
        return dao.insertSelective(record);
    }

    @Override
    public int update(CommonRa record) {
        record.setUpdateTime(new Date());
        int result = dao.updateByPrimaryKeySelective(record);
        return result;
    }

    @Override
    public int delete(Long id) {
        int result = dao.deleteByPrimaryKey(id);
        return result;
    }

}
